<template>
  <div class="detail" id="notebook-list">
    <header>
      <a href="#" class="button" @click.stop.prevent="onCreate">
        <svg class="icon">
          <use xlink:href="#icon-add"></use>
        </svg>
        新建笔记本</a>
    </header>
    <main>
      <div class="layout">
        <h3>笔记本列表({{ notebooks.length }})</h3>
        <div class="book-list">
          <router-link v-for="notebook in notebooks" :key="notebook" :to="`/note?notebookId=${notebook.id}`"
                       class="notebook">
            <div>
              <svg class="icon">
                <use xlink:href="#icon-notebooks"></use>
              </svg>
              {{ notebook.title }}
              <span>{{ notebook.noteCounts }}</span>
              <span class="action" @click.stop.prevent="onEdit(notebook)">编辑</span>
              <span class="action" @click.stop.prevent="onDelete(notebook)">删除</span>
              <span class="date">{{ notebook.createdAtFriendly }}</span>
            </div>
          </router-link>
        </div>
      </div>
    </main>
  </div>

</template>

<script>
import {ElMessageBox} from 'element-plus'
import {mapGetters, mapActions} from 'vuex'
import Auth from '@/apis/author'

export default {
  data() {
    return {}
  },
  created() {
    Auth.getInfo().then(res => {
      if (!res.isLogin) {
        this.$router.push({path: '/login'})
      }
    })
    this.getNotebooks()
  },
  computed: {
    ...mapGetters(['notebooks'])
  },
  methods: {
    ...mapActions([
      'getNotebooks',
      'addNotebook',
      'updateNotebook',
      'deleteNotebook',
    ]),
    onCreate() {
      ElMessageBox.prompt('输入新笔记本标题', '创建笔记本', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{1,30}$/,
        inputErrorMessage: '标题不能为空，且不超过30个字符',
      }).then(({value}) => {
        this.addNotebook({title: value})
      })
    },
    onEdit(notebook) {
      // eslint-disable-next-line no-unused-vars
      let title = ''
      ElMessageBox.prompt('输入新笔记本标题', '修改笔记本', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{1,30}$/,
        inputValue: notebook.title,
        inputErrorMessage: '标题不能为空，且不超过30个字符',
      }).then(({value}) => {
        this.updateNotebook({notebookId: notebook.id, title: value})
      })
    },
    onDelete(notebook) {
      ElMessageBox.confirm(
          '确认要删除笔记本吗?',
          '删除笔记本',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
        this.deleteNotebook({notebookId: notebook.id})
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import url(../assets/css/notebook-list);

</style>